<?php

namespace App\Http\Controllers\Wx;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Curl;
use Cache;

/**
 * wx小程序
 */
class WxController extends Controller
{
    private $appid;
    private $secret;
    const BASE_RUI = 'https://api.weixin.qq.com';
    const MAX_CONNECT_NUM = 2; // 最大连接次数
    // GET
    const JSCODE2SESSION = '/sns/jscode2session';
    const TOKEN = '/cgi-bin/token';
    public function __construct()
    {
        $this->appid = env('WX_APPID');
        $this->secret = env('WX_SECRET');
    }
    /**
     *  wx.login 接口获得临时登录凭证 code 后传到开发者服务器调用此接口完成登录流程
     *
     * @param Request $code
     * @return json{session_key: "OhTQ27fTU1UHSlbDl9exLQ==", openid: "o5aVPwQ2j2g-r7VzoaEl-FzomGEY"}
     */
    public function code2Session(Request $request)
    {
        $code = $request->code ?: '';
        $url = self::BASE_RUI . self::JSCODE2SESSION;
        $data = [
            'appid' => $this->appid,
            'secret' => $this->secret,
            'js_code' => $code,
            'grant_type' => 'authorization_code',
        ];
        function getinfo($url, $data)
        {
            return Curl::to($url)
                ->withData($data)
                ->asJson()
                ->get();
        }
        $res = null;
        foreach (range(0, self::MAX_CONNECT_NUM - 1) as $row) {
            $res = getinfo($url, $data);
            if (isset($res->errcode) && $res->errcode === -1) {
                // 微信服务器繁忙，0.5秒后再试
                usleep(0.5 * 1000000);
                $res = getinfo($url, $data);
            } else {
                break;
            }
        }
        if (isset($res->errcode)) {
            return resJson($res->errcode, $res->errmsg);
        }

        return resJson(self::HTTP_0_SUCCESS, $res);
    }
    /**
     * 获取小程序全局唯一后台接口调用凭据（access_token）,缓存7200秒
     *  @param Request $code
     *  @return json{access_token: "26_nBfVDHX-7PSWuZCxbQfxUuILVF_eItG1goTV2aSFybi92DNmkgydRtNU7MN7rcI8qIWUnBzZEvlT5iTEJlw4b_VqHgid9TNd3vW55pkVJpCMKQNPAIaDF-ha7f0GBUgAGAZUN"==", expires_in: 7200}
     */
    public function getAccessToken(Request $request)
    {
        if (Cache::has(self::MINI_APP_ACCESSTOKEN)) {
            $obj = new \stdClass;
            $obj->access_token = Cache::get(self::MINI_APP_ACCESSTOKEN);
            return json_encode($obj);
        } else {
            $url = self::BASE_RUI . self::TOKEN;
            $data = [
                'appid' => $this->appid,
                'secret' => $this->secret,
                'grant_type' => 'client_credential',
            ];
            function getinfo($url, $data)
            {
                return Curl::to($url)
                    ->withData($data)
                    ->asJson()
                    ->get();
            }
            $res = null;
            foreach (range(0, self::MAX_CONNECT_NUM - 1) as $row) {
                $res = getinfo($url, $data);
                if (isset($res->errcode) && $res->errcode === -1) {
                    // 微信服务器繁忙，0.5秒后再试
                    usleep(0.5 * 1000000);
                    $res = getinfo($url, $data);
                } else {
                    break;
                }
            }
            if (isset($res->access_token)) {
                Cache::put(self::MINI_APP_ACCESSTOKEN, $res->access_token, $res->expires_in - 200);
            }
            return json_encode($res);
        }
    }
}
